<?php

class SendEmail {

  var $ci;

  function __construct() {
    $this->ci = & get_instance();
    $this->ci->load->model('setting_model');
  }  

  function sendViaLocalhost($data) {
    if (strtoupper(substr(PHP_OS, 0, 3) == 'WIN')) {
      $eol = "\r\n";
    } elseif (strtoupper(substr(PHP_OS, 0, 3) == 'MAC')) {
      $eol = "\r";
    } else {
      $eol = "\n";
    }
    $headers = 'From: ' . $data['from'] . $eol;
    $headers .= 'Reply-To: ' . $data['from'] . $eol;
    $headers .= 'Return-Path: ' . $data['from'] . $eol;
    $headers .= "Message-ID:<" . time() . " TheSystem@" . $_SERVER['SERVER_NAME'] . ">" . $eol;
    $headers .= "X-Mailer: PHP v" . phpversion() . $eol;
    $mime_boundary = md5(uniqid(time()));
    $headers .= "MIME-Version: 1.0" . $eol;
    $headers .= "Content-Type: multipart/mixed; boundary=\"" . $mime_boundary . "\"" . $eol . $eol;
    $headers .= "This is a multi-part message in MIME format." . $eol;
    $headers .= "--" . $mime_boundary . $eol;
    $headers .= "Content-type: text/html; charset=windows-874" . $eol; // or UTF-8 //  
    $headers .= "Content-Transfer-Encoding: 7bit" . $eol . $eol;
    $headers .= $data['content'] . $eol . $eol;
    $msg = '';
    if (!empty($data['attach'])) {
      if (!is_array($data['attach'])) {
        $data['attach'] = array($data['attach']);
      }
      foreach ($data['attach'] as $attach) {
        $handle = fopen($attach, 'rb');
        $f_contents = fread($handle, filesize($attach));
        $f_contents = chunk_split(base64_encode($f_contents));
        $f_type = filetype($attach);
        $file_name = basename($attach);
        fclose($handle);
        $msg = "--" . $mime_boundary . $eol;
        $msg .= "Content-Type: application/$f_type; name=\"" . $file_name . "\"" . $eol;
        $msg .= "Content-Transfer-Encoding: base64" . $eol;
        $msg .= "Content-Disposition: attachment; filename=\"" . $file_name . "\"" . $eol . $eol;
        $msg .= $f_contents . $eol . $eol;
      }
      $msg .= "--" . $mime_boundary . "--" . $eol . $eol;
    }
    # SEND THE EMAIL
    return mail($data['to'], $data['subject'], $msg, $headers);
  }
  
  function _getMailer() {
    $this->ci->load->library('phpMailer');
    $mail = new PhpMailer();
    $mail->IsSMTP(); // telling the class to use SMTP
    // enables SMTP debug information (for testing)
    // 1 = errors and messages
    // 2 = messages only
    //$mail->SMTPDebug = 2;

    $mail->SMTPAuth = true;                  // enable SMTP authentication
    $mail->Host = $this->ci->setting_model->item("smtp_host"); // SMTP server
    $mail->Port = $this->ci->setting_model->item("smtp_port"); // set the SMTP port for the GMAIL server
    $mail->Username = $this->ci->setting_model->item("smtp_username"); // SMTP account username
    $mail->Password = $this->ci->setting_model->item("smtp_password"); // SMTP account password
//    $mail->SMTPSecure = $this->ci->setting_model->item("SMTPSecure"); // SMTP secure
//    $mail->CharSet = $this->ci->setting_model->item("mail_charSet");
    $mail->FromName = $this->ci->setting_model->item("sender_name");
    return $mail;
  }
  
  function sendViaServerSMTP($data){
    $mail = $this->_getMailer();
    if (isset($data['from']) && isset($data['to']) &&
            isset($data['subject']) && $this->ci->setting_model->item('enable_email') == TRUE) {
      $mail->FromName = $data['from'];
      $mail->AddAddress($data['to']);
      if (isset($data['cc'])) {
        $mail->AddCC($data['cc']);
      }
      if (isset($data['bcc'])) {
        $mail->AddBCC($data['bcc']);
      }
      $mail->Subject = $data['subject'];
      $mail->MsgHTML($data['content']);
      try{
        return $mail->Send();        
      } catch(Exception $ex){
        return false;
      }
    } else
      return FALSE;
  }
  
  function send($data){
    if($this->ci->setting_model->item('mail_protocol')){	  
      return $this->sendViaLocalhost($data);
    } else {
      return $this->sendViaServerSMTP($data);
    }
  }

  function sendEmailByTemplate($data, $templateKey) {
    if (isset($data['from']) && isset($data['to']) && $this->ci->setting_model->item('enable_email') == TRUE) {
      $this->ci->load->model('email_template_model');
      $template = $this->ci->email_template_model->getContent($templateKey);
      if(!empty($template)){
        $data['content'] = $this->getContentByTemplate($data, empty($template['content'])? '' : $template['content']);
      } else $data['content'] = '';
      try {
        if ($this->send($data))
          return true;
      } catch (Exception $e) {}
      return false;
    } else {
      return true;
    }
  }

  function sendEmail($data) {
    if (isset($data['from']) && isset($data['to']) &&
            isset($data['subject']) && $this->ci->setting_model->item('enable_email') == TRUE) {
      try {
        if ($this->send($data)) {
          return true;
        }
      } catch (Exception $e) {
        
      }
      return false;
    } else {
      return true;
    }
  }

  function getContentByTemplate($data, $content) {
    foreach ($data as $key => $value) {
      $content = str_replace('[' . $key . ']', $value, $content);
    }
    return $content;
  }

}